<?php
/**
 * Created by sublime
 * User: 姚鹏
 * Date: 2017-11-01
 * Time: 15:51
 */
namespace app\mall\controller;
use controller\BasicAdmin;
use service\DataService;
use think\Db;
use app\comm\service\AdminUserService;
use app\mall\model\User as UserModel;
class User extends BasicAdmin
{
	public $table = "User";
	/**
	 * 会员信息首页
	 * @Author   lingyun
	 * @DateTime 2017-11-29T14:36:01+0800
	 * @return   [type]                   [description]
	 */
	public function index(){
		$this->title = '会员管理';
        $get = $this->request->get();
        $join = [
        	['ys_store b','a.store_id=b.id','LEFT'],
        	['ys_sys_level c','a.level_id=c.id','LEFT']
        ];
        $db = Db::name('user')->alias('a')->join($join)->where('a.is_deleted',0)->field('a.*,b.title,c.title as level')->order('uid desc');
        if(!empty($get['realname'])){
            $map['a.mobile|a.pay_code'] = ['like','%'.$get['realname'].'%'];
            (isset($get['realname']) && $get['realname'] !== '') && $db->where($map);
        }
        $yangshi = config("qiniu");
        $this->assign('yangshi',$yangshi['yangshi']);          //七牛样式后缀
        return parent::_list($db);
	}	
	/**
	 * 新增会员
	 * @Author   lingyun
	 * @DateTime 2017-11-29T10:12:19+0800
	 */
	public function add(){
		if(request()->isPost()){
			$post = input('post.');
			$usermodel = new UserModel();		
			$res = $usermodel->add_edit($post);
			$res['code']==1?$this->success('保存成功',''):$this->error($res['msg'],'');
		}
		return $this->_form($this->table, 'form');
	}
	/**
	 * 编辑会员
	 * @Author   lingyun
	 * @DateTime 2017-11-29T10:13:18+0800
	 * @return   [type]                   [description]
	 */
	public function edit(){
		if(request()->isPost()){
			$post = input('post.');
			$usermodel = new UserModel();		
			$res = $usermodel->add_edit($post);
			$res['code']==1?$this->success('保存成功',''):$this->error($res['msg'],'');
		}
		return $this->_form($this->table, 'form');
	}
	/**
	 * 修改密码
	 * @Author   lingyun
	 * @DateTime 2017-11-29T10:48:33+0800
	 * @return   [type]                   [description]
	 */
	public function pass(){
		if(request()->isPost()){
			$post = input('post.');
			$usermodel = new UserModel();		
			$res = $usermodel->pass($post);
			$res['code']==1?$this->success('保存成功',''):$this->error($res['msg'],'');
		}
		return $this->_form($this->table,'pass');
	}
	/**
	 * 变更会员余额
	 * @Author   lingyun
	 * @DateTime 2017-11-29T11:29:08+0800
	 * @return   [type]                   [description]
	 */
	public function change_credit(){
		if(request()->isPost()){
			$post = input('post.');
			if($post['chargetype'] == 1){		//消费，减少
				$res = Db::name('user')->where('uid',$post['uid'])->setDec('user_money',$post['amount']);//减少价格
			}else if($post['chargetype'] == 2){
			    $user = db('user')->where('uid',$post['uid'])->field('uid,level_id,user_money')->find();
                $cur_level = user_level($post['amount'],$user);
                $cur_level = $user['level_id']<=$cur_level?$cur_level:$user['level_id'];
                $cur_money = $user['user_money'] + $post['amount'];
                $res = db('user')->where('uid',$post['uid'])->update(['level_id'=>$cur_level,'user_money'=>$cur_money]);
			}
			if($res !== false){
				$user = Db::name('user')->where('uid',$post['uid'])->field('uid,user_money,store_id,realname')->find();
				$admin_id = session('user')['id'];
				$data = array('uid'=>$user['uid'],'admin_id'=>$admin_id,'store_id'=>$user['store_id'],'order_id'=>0,'order_sn'=>0,'uname'=>$user['realname'],'amount'=>$post['amount'],'cur_amount'=>$user['user_money'],'sign'=>1,'chargetype'=>$post['chargetype'],'charge_cn'=>$post['charge_cn'],'addtime'=>time());
				$res = Db::name('user_wallet_log')->insertGetId($data);
				$res>0?$this->success('保存成功',''):$this->error('保存失败','');
			}else{
				$this->error('保存失败','');
			}
		}
		return $this->_form($this->table,'change_credit');
	}
	/**
	 * 变更会员积分
	 * @Author   lingyun
	 * @DateTime 2017-11-29T14:36:21+0800
	 * @return   [type]                   [description]
	 */
	public function change_point(){
		if(request()->isPost()){
			$post = input('post.');
			if($post['type'] == 0){		//消费，减少
				$res = Db::name('user')->where('uid',$post['uid'])->setDec('pay_points',$post['point']);//减少价格
                $point = '-'.$post['point'];
			}else if($post['type'] == 1){
				$res = Db::name('user')->where('uid',$post['uid'])->setInc('pay_points',$post['point']);//增加价格
                $point = $post['point'];
			}
			if($res !== false){
				$user = Db::name('user')->where('uid',$post['uid'])->field('uid,pay_points,store_id,realname')->find();
				$admin_id = session('user')['id'];
				$data = array('uid'=>$user['uid'],'admin_id'=>$admin_id,'store_id'=>$user['store_id'],'order_id'=>0,'uidtype'=>2,'signid'=>0,'type'=>$post['type'],'point'=>$point,'curpoint'=>$user['pay_points'],'type_cn'=>$post['type_cn'],'remark'=>$post['type_cn'],'whname'=>'后台操作','addtime'=>time());
				$res = Db::name('user_point_log')->insertGetId($data);
				$res>0?$this->success('保存成功',''):$this->error('保存失败','');
			}else{
				$this->error('保存失败','');
			}
		}
		return $this->_form($this->table,'change_point');
	}
	
	/**
	 *用户优惠券
	 */
	public function eidtuser(){
		$userservice = new AdminUserService;
		$id = $this->request->get('id');
		$user = $userservice -> getuser($id);
		$post = $this->request->post();
		if(!empty($post)){
			 $res = $userservice->updateuser($post);
			 if( $res ==3){
			 	$this->error('不好意思，积分不够减!', '');
			 }
			 $this->success('恭喜, 数据保存成功!', '');	
		}
		
		return  $this->fetch('',['user'=>$user]);
	}

	/**
	 * 余额后台变更
	 * @return [type] [description]
	 */
	public function eidtuserlepoin(){
		$userservice = new AdminUserService;
		if (request()->isGet()){
			$id = $this->request->get('id');
			$user = $userservice -> getuser($id);
			return  $this->fetch('',['user'=>$user]);
		}
		if (request()->isPost()){
			$post = $this->request -> post();
			$sle = $userservice  -> asdesmoney($post);
			if($sle==1){
				 $this->success('恭喜, 操作成功!', '');	
			}
			if($sle==0){
				$this->error('不好意思，保存失败!', '');
			}
			if($sle==3){
				$this->error('你的余额不足', '');
			}	
		}
	}
	/**
	 * 会员余额记录
	 * @return [type] [description]
	 */
	public function credit_log(){
		$uid = input('uid');
		$map['a.uid'] = array('eq',$uid);
		$map['a.is_deleted'] = array('eq',0);
		$join = [
			['ys_user b', 'a.uid=b.uid', 'LEFT'],
			['ys_system_user c','a.admin_id=c.id','LEFT']
		];
        $get = $this->request->get();
		if (isset($get['date']) && $get['date'] !== '') {
            list($start, $end) = explode('-', str_replace(' ', '', $get['date']));
            $start = strtotime($start);   
            $end = strtotime($end);
            $map['a.addtime'] = array(array('gt',$start),array('lt',$end),'AND');
            $this->assign('date',$get['date']);
        }else{
        	$this->assign('date','');
        }
        // var_dump($map);exit();
		$db = Db::name('user_wallet_log')->alias('a')->join($join)->where($map)->field('a.*,b.nickname,c.username')->order('addtime desc');
		$this->assign('title','会员余额纪录');
		$this->assign('uid',$uid);
        return parent::_list($db);
	}
	/**
	 * 会员积分记录
	 * @return [type] [description]
	 */
	public function point_log(){
		$uid = input('uid');
		$map['a.uid'] = array('eq',$uid);
		$join = [
			['ys_user b', 'a.uid=b.uid', 'LEFT'],
			['ys_system_user c','a.admin_id=c.id','LEFT']
		];
        $get = $this->request->get();
		if (isset($get['date']) && $get['date'] !== ''){
            list($start, $end) = explode('-', str_replace(' ', '', $get['date']));
            $start = strtotime($start);   
            $end = strtotime($end);
            $map['a.addtime'] = array(array('gt',$start),array('lt',$end),'AND');
            $this->assign('date',$get['date']);
        }else{
        	$this->assign('date','');
        }
        // var_dump($map);exit();
		$db = Db::name('user_point_log')->alias('a')->join($join)->where($map)->field('a.*,b.nickname,c.username')->order('id desc');
		$this->assign('title','会员积分纪录');
		$this->assign('uid',$uid);
        return parent::_list($db);
	}

    /**
     * @Author  lingyun
     * @Desc    设置会员状态
     */
	public function set_status(){
        $id = input('id');
        $status = db('user')->where('uid',$id)->value('status');
        $status = abs($status-1);
        $res = db('user')->where('uid',$id)->update(['status'=>$status]);
        $res!==false?$this->success('设置成功',''):$this->error('设置失败，请稍后再试','');
    }


    /**
     * @Author  lingyun
     * @Desc    添加 -- 编辑会员
     */
    public function add_edit_member(){
        if(request()->isPost()){
            $post = input('post.');
            $reg_mobile = '/^1[3-9][0-9]{9}$/';
            $reg_password = '/^[a-zA-Z0-9_]{6,16}$/';
            if(empty($post['realname'])){
                $this->error('请输入真实姓名','');
            }
//            if($post['mobile'] == ''){
//                $this->error('请填写手机号','');
//            }
            if(!empty($post['mobile'])){
                if(!preg_match($reg_mobile,$post['mobile'])){
                    $this->error('手机格式错误','');
                }
                $mobile = db('user')->where('mobile',$post['mobile'])->find();
                if(!empty($mobile)){
                    $this->error('该手机号已被占用，请更换手机号','');
                }
            }
            if(empty(trim($post['password']))){
                $this->error('请填写登录密码','');
            }
            if(!preg_match($reg_password,$post['password'])){
                $this->error('密码格式错误，必须是字母数字下划线6~16位组合','');
            }
            if($post['password'] != $post['repassword']){
                $this->error('两次密码输入不一致，请重新输入','');
            }

            $user = db('user')->order('uid desc')->limit(1)->value('uid');
            $cur_uid = $user+1;
//            $pay_code = '5270'.sprintf("%04d", $cur_uid);         //会员支付码
            if(!empty($post['pay_code'])){          //指定会员卡号
                $pay_code_res = db('user')->where('pay_code',$post['pay_code'])->find();
                if(!empty($pay_code_res)){
                    $this->error('该会员卡号已被占用，请重新填写','');
                }else{
                    $pay_code = $post['pay_code'];
                }
            }else{
                $pay_code = '5270'.sprintf("%04d", $cur_uid);         //会员支付码
            }
            $data_arr = [
                't_pid'=>0,
                'pid'=>0,
                'mobile'=>$post['mobile'],
                'realname'=>$post['realname'],
                'nickname'=>$post['realname'],
                'password'=>md5($post['password']),
                'pay_code'=>$pay_code,
                'addtime'=>time(),
                'pay_points'=>100,
                'level_id'=>1
            ];
            $res = $u_id = db('user')->insertGetId($data_arr);
            $user_point_log = [
                'uid'=>$u_id,
                'store_id'=>session('user.store_id'),
                'uidtype'=>2,
                'signid'=>4,
                'type'=>1,
                'point'=>100,
                'curpoint'=>100,
                'type_cn'=>'注册会员赠送积分',
                'whname'=>'后台操作',
                'remark'=>'注册会员赠送积分',
                'addtime'=>time(),
            ];

            db('user_point_log')->insert($user_point_log);

            $res>0?$this->success('保存成功',''):$this->error('保存失败','');
        }else{
            $id = input('id');
            $info = db('user')->where('uid',$id)->find();      //会员信息

            $this->assign('vo',$info);
            return $this->fetch();
        }
    }

    /**
     * @Author  lingyun
     * @Desc    是否发放生日蛋糕
     * 2018-06-18
     */
    public function birth(){
        $year = date('Y',time());
        $month = date('n',time());
        $day = $this->get_birth_day();
        $last_time = $year.'-12-31';
        $last_time = strtotime($last_time);

        $map['is_deleted'] = ['eq',0];
        $map['birthday_month'] = ['eq',$month];
        $map['is_birth'] = ['lt',$last_time];
        $map['birthday_day'] = array(array('egt',$day['start']),array('elt',$day['end']),'AND');
        if(!empty(input('realname'))){
            $realname = input('realname');
            $map['realname'] = ['like','%'.$realname.'%'];
        }
//halt($map);
        $db = db('user')->where($map)->field('uid,realname,pay_code,nickname,mobile,birthday_year,birthday_month,birthday_day,level_id,is_birth');

        $this->assign('title','生日提醒');

        return parent::_list($db);
    }

    /**
     * @Author  lingyun
     * @Desc    生日蛋糕
     * 2018-06-18
     */
    private function get_birth_day(){
        $timestamp = time();
        $start = date("j",mktime(0, 0 , 0,date("m"),date("d")-date("w")+1,date("Y")));
        $end = date("j",mktime(23,59,59,date("m"),date("d")-date("w")+7,date("Y")));

        return ['start'=>$start,'end'=>$end];
    }

    /**
     * @Author  lingyun
     * @Desc    设置发放生日蛋糕
     */
    public function set_birth(){
        $uid = input('id');

        $res = db('user')->where('uid',$uid)->update(['is_birth'=>time()]);
        $res!==false?$this->success('设置成功',''):$this->error('设置失败','');
    }


}
?>